// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    gridCol: 5,
    is_android: true,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad(options) {
    let site = options.site
    let name = options.name
    let code = options.code
    var now = Date.parse(new Date())
    this.getPowerinfo(code)
    this.setData({
      name,
      site,
      code,
      now
    })
    wx.stopPullDownRefresh()
    // console.log(this.data.now)
  },
  chooseItem(t) {
    if (wx.getStorageSync('loged') == true) {
      var _this = this
      if (wx.getStorageSync('os') == 'ios') {
        this.setData({
          is_android: false,
        })
      }
      wx.showActionSheet({
        itemList: ['2小时 0.60元', '4小时 1.20元', '6小时 1.80元', '8小时 2.40元', '10小时 3.00元'],
        success(res) {
          console.log(res.tapIndex)
          let n = res.tapIndex
          var m = (n + 1) * 60
          wx.showModal({
            title: t.currentTarget.dataset.slotid + '号充电桩',
            content: '是否支付' + (m / 100).toFixed(2) + '元，充电' + m * 2 + '分钟？',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                wx.showLoading({
                  title: '加载中',
                })
                wx.cloud.callFunction({
                  name: "setPowerOn",
                  data: {
                    os: _this.data.is_android ? 'android' : 'ios',
                    userId: wx.getStorageSync('user').id,
                    token: wx.getStorageSync('token'),
                    slotId: t.currentTarget.dataset.slotid,
                    hostId: t.currentTarget.dataset.hostid,
                    fee: m
                  }
                }).then(res => {
                  console.log(res)
                  let bkdata = JSON.parse(res.result)
                  wx.hideLoading()
                  if (bkdata.code == 0) {
                    wx.showToast({
                      title: '您可用使用充电桩了~',
                    })
                    wx.navigateTo({
                      url: '/pages/order/order',
                    })
                  } else if (bkdata.code == -1) {
                    wx.showToast({
                      title: '当前设备已被占用',
                    })
                  } else {
                    wx.showToast({
                      title: '系统错误！',
                    })
                  }
                }).catch(res => {
                  console.log("失败", res)
                  wx.showToast({
                    title: '系统错误！',
                    icon: 'none'
                  })
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })

        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    } else {
      wx.showModal({
        title: t.currentTarget.dataset.slotid + '号充电桩',
        content: '当前充电桩状态可用！授权登录后可在线下单，是否前往首页进行登录？',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.switchTab({
              url: '/pages/start/start',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }

  },
  getAlloverTime(t) {
    console.log(t)
    let n = t.startTime
    let m = t.minutes
    var timestamp = Date.parse(new Date())
    var remaintime = parseInt(m - (timestamp - n) / 60 / 1000)
    console.log(remaintime)
    if (0 < remaintime &&  remaintime <= 30) {
      wx.showModal({
        title: t.slotId + '号充电桩',
        content: '剩余时间' + remaintime + '分种',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  getOverTime(t) {
    console.log(t)
    let n = t.currentTarget.dataset.start
    let m = t.currentTarget.dataset.minutes
    var timestamp = Date.parse(new Date())
    var remaintime = parseInt(m - (timestamp - n) / 60 / 1000)
    console.log(remaintime)
    wx.showModal({
      title: t.currentTarget.dataset.id + '号充电桩',
      content: '剩余时间' + remaintime + '分种',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  gridchange: function (e) {
    this.setData({
      gridCol: e.detail.value
    });
  },
  gridswitch: function (e) {
    this.setData({
      gridBorder: e.detail.value
    });
  },
  menuBorder: function (e) {
    this.setData({
      menuBorder: e.detail.value
    });
  },
  menuArrow: function (e) {
    this.setData({
      menuArrow: e.detail.value
    });
  },
  menuCard: function (e) {
    this.setData({
      menuCard: e.detail.value
    });
  },
  switchSex: function (e) {
    this.setData({
      skin: e.detail.value
    });
  },

  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  // getPowerinfo(){
  //   let _this = this
  //   wx.request({
  //     url: 'http://47.104.75.15/campus/api/power/slots', //仅为示例，并非真实的接口地址
  //     data: {
  //     code:'CDZ0533LG0400'
  //     },
  //     header: {
  //       'content-type': 'application/x-www-form-urlencoded' // 默认值
  //     },
  //     success (res) {
  //       console.log(res,'power')
  //       _this.setData({
  //        solts:res.data.data
  //       })
  //     }
  //   })
  // },
  getPowerinfo(t) {
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.callFunction({
      name: "getPowerInfo",
      data: {
        code: t
      }
    }).then(res => {
      wx.hideLoading()
      console.log("成功", res)
      let bkdata = JSON.parse(res.result)
      console.log('cdz', bkdata)
      this.setData({
        solts: bkdata.data
      })
      var i
      for (i = 0; i <= bkdata.data.length - 1; i++) {
        if (bkdata.data[i].powerState == 1 && bkdata.data[i].status == 0) {
          this.getAlloverTime(bkdata.data[i])
        }
      }
      //console.log(bkdata)
    }).catch(res => {
      console.log("失败", res)
      wx.showToast({
        title: '充电桩信息查询失败！',
        icon: 'none'
      })
    })
  },
  canNotUsepower() {
    wx.showToast({
      title: '当前设备已禁用',
      icon: 'none'
    })
  },
  Nav() {
    wx.switchTab({
      url: '/pages/user/user',
    })
  },
  onPullDownRefresh() {
    const a = []
    a.site = this.data.site
    a.name = this.data.name
    a.code = this.data.code
    this.onLoad(a)
  },
  onShareAppMessage: function (res) {
    return {
      title: '校园充电桩小助手来了！',
      path: '/pages/index/index?code=' + this.data.code + '&site=' + this.data.site + '&name=' + this.data.name
    }
  },
  onShareTimeline: function (res) {
    return {
      title: '校园充电桩小助手来了！',
      query: 'code=' + this.data.code + '&site=' + this.data.site + '&name=' + this.data.name
    }
  },
})